package com.example.baselibrary.utils

import android.content.Context
import android.graphics.drawable.Drawable
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity

/**
 * 图片加载工具类，封装Glide防止内存泄漏
 */
object ImageLoaderUtils {

    /**
     * 缓存策略枚举
     */
    enum class CacheStrategy {
        ALL,     // 缓存原始数据和结果
        NONE,    // 不缓存
        DATA,    // 只缓存原始数据
        RESOURCE // 只缓存结果
    }

    /**
     * 加载网络图片到ImageView
     * @param context 上下文（Activity或Fragment）
     * @param url 图片URL
     * @param imageView 目标ImageView
     * @param placeholderId 占位图资源ID（可选）
     * @param errorId 错误图片资源ID（可选）
     */
    fun loadImage(
        context: Context,
        url: String,
        imageView: ImageView,
        placeholderId: Int? = null,
        errorId: Int? = null
    ) {
        if (context.isContextValid()) {
            var requestBuilder = Glide.with(context).load(url)

            // 设置占位图
            placeholderId?.let {
                requestBuilder = requestBuilder.placeholder(it)
            }

            // 设置错误图片
            errorId?.let {
                requestBuilder = requestBuilder.error(it)
            }

            requestBuilder.into(imageView)
        }
    }

    /**
     * 在Fragment中加载图片
     */
    fun loadImage(
        fragment: Fragment,
        url: String,
        imageView: ImageView,
        placeholderId: Int? = null,
        errorId: Int? = null
    ) {
        if (!fragment.isDetached) {
            var requestBuilder = Glide.with(fragment).load(url)

            placeholderId?.let {
                requestBuilder = requestBuilder.placeholder(it)
            }

            errorId?.let {
                requestBuilder = requestBuilder.error(it)
            }

            requestBuilder.into(imageView)
        }
    }

    /**
     * 加载圆形图片
     */
    fun loadCircleImage(
        context: Context,
        url: String,
        imageView: ImageView,
        placeholderId: Int? = null
    ) {
        if (context.isContextValid()) {
            val options = RequestOptions.circleCropTransform()
            placeholderId?.let {
                options.placeholder(it)
            }

            Glide.with(context)
                .load(url)
                .apply(options)
                .into(imageView)
        }
    }

    /**
     * 加载圆角图片
     */
    fun loadRoundImage(
        context: Context,
        url: String,
        imageView: ImageView,
        radius: Int,
        placeholderId: Int? = null
    ) {
        if (context.isContextValid()) {
            val options = RequestOptions.bitmapTransform(RoundedCorners(radius))
            placeholderId?.let {
                options.placeholder(it)
            }

            Glide.with(context)
                .load(url)
                .apply(options)
                .into(imageView)
        }
    }

    /**
     * 带回调的图片加载
     */
    fun loadImageWithCallback(
        context: Context,
        url: String,
        imageView: ImageView,
        listener: (Boolean) -> Unit,
        placeholderId: Int? = null,
        errorId: Int? = null
    ) {
        if (context.isContextValid()) {
            var requestBuilder = Glide.with(context).load(url)

            placeholderId?.let {
                requestBuilder = requestBuilder.placeholder(it)
            }

            errorId?.let {
                requestBuilder = requestBuilder.error(it)
            }

            requestBuilder.listener(object : RequestListener<Drawable> {
                override fun onLoadFailed(
                    e: com.bumptech.glide.load.engine.GlideException?,
                    model: Any?,
                    target: Target<Drawable>?,
                    isFirstResource: Boolean
                ): Boolean {
                    listener(false)
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable?,
                    model: Any?,
                    target: Target<Drawable>?,
                    dataSource: com.bumptech.glide.load.DataSource?,
                    isFirstResource: Boolean
                ): Boolean {
                    listener(true)
                    return false
                }
            }).into(imageView)
        }
    }

    /**
     * 预加载图片到缓存
     */
    fun preloadImage(context: Context, url: String) {
        if (context.isContextValid()) {
            Glide.with(context)
                .load(url)
                .preload()
        }
    }

    /**
     * 加载GIF图片
     */
    fun loadGif(context: Context, url: String, imageView: ImageView, placeholderId: Int? = null) {
        if (context.isContextValid()) {
            var requestBuilder = Glide.with(context).asGif().load(url)
            placeholderId?.let {
                requestBuilder = requestBuilder.placeholder(it)
            }
            requestBuilder.into(imageView)
        }
    }

    /**
     * 带缓存策略的图片加载
     */
    fun loadImageWithCacheStrategy(
        context: Context,
        url: String,
        imageView: ImageView,
        strategy: CacheStrategy,
        placeholderId: Int? = null
    ) {
        if (context.isContextValid()) {
            val requestBuilder = Glide.with(context).load(url)

            val requestOptions = when (strategy) {
                CacheStrategy.ALL -> RequestOptions()
                CacheStrategy.NONE -> RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE)
                CacheStrategy.DATA -> RequestOptions().diskCacheStrategy(DiskCacheStrategy.DATA)
                CacheStrategy.RESOURCE -> RequestOptions().diskCacheStrategy(DiskCacheStrategy.RESOURCE)
            }

            placeholderId?.let {
                requestOptions.placeholder(it)
            }

            requestBuilder.apply(requestOptions).into(imageView)
        }
    }

    /**
     * 清除ImageView中的图片加载任务
     */
    fun clearImage(context: Context, imageView: ImageView) {
        if (context.isContextValid()) {
            Glide.with(context).clear(imageView)
        }
    }

    /**
     * Builder模式加载图片
     */
    fun load(context: Context, url: String): ImageLoadBuilder {
        return ImageLoadBuilder(context, url)
    }

    /**
     * 检查Context是否有效，防止内存泄漏
     */
    private fun Context.isContextValid(): Boolean {
        return when (this) {
            is FragmentActivity -> !this.isFinishing && !this.isDestroyed && !this.isRestricted
            is android.view.ContextThemeWrapper -> this.baseContext.isContextValid()
            else -> true
        }
    }
}

/**
 * Builder模式图片加载器
 */
class ImageLoadBuilder(private val context: Context, private val url: String) {
    private var placeholderId: Int? = null
    private var errorId: Int? = null
    private var isCircleCrop = false
    private var cornerRadius = 0
    private var cacheStrategy: ImageLoaderUtils.CacheStrategy? = null
    private var listener: ((Boolean) -> Unit)? = null

    fun placeholder(resId: Int): ImageLoadBuilder {
        this.placeholderId = resId
        return this
    }

    fun error(resId: Int): ImageLoadBuilder {
        this.errorId = resId
        return this
    }

    fun circleCrop(): ImageLoadBuilder {
        this.isCircleCrop = true
        return this
    }

    fun roundedCorners(radius: Int): ImageLoadBuilder {
        this.cornerRadius = radius
        return this
    }

    fun cacheStrategy(strategy: ImageLoaderUtils.CacheStrategy): ImageLoadBuilder {
        this.cacheStrategy = strategy
        return this
    }

    fun listener(listener: (Boolean) -> Unit): ImageLoadBuilder {
        this.listener = listener
        return this
    }

    fun into(imageView: ImageView) {
        when {
            listener != null -> {
                ImageLoaderUtils.loadImageWithCallback(context, url, imageView, listener!!, placeholderId, errorId)
            }
            cacheStrategy != null -> {
                ImageLoaderUtils.loadImageWithCacheStrategy(context, url, imageView, cacheStrategy!!, placeholderId)
            }
            isCircleCrop -> {
                ImageLoaderUtils.loadCircleImage(context, url, imageView, placeholderId)
            }
            cornerRadius > 0 -> {
                ImageLoaderUtils.loadRoundImage(context, url, imageView, cornerRadius, placeholderId)
            }
            else -> {
                ImageLoaderUtils.loadImage(context, url, imageView, placeholderId, errorId)
            }
        }
    }
}
